package concurrent;

/**
 * @Author tuyou_cd
 * @Date 2020/8/19 12:17
 */
public class SynchronizedTest {

    public static void main(String[] args) throws InterruptedException {

        SynchronizedTest test = new SynchronizedTest();
        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test.otherMethod(); //调用未加锁的方法不会阻塞
                System.out.println("子线程尝试获取锁");
                synchronized (test) {
                    System.out.println("子线程获取锁成功");
                }
            }
        }.start();

        test.lock();
    }

    public synchronized void lock() throws InterruptedException {
        System.out.println("获取到锁");
        Thread.sleep(3000);
        System.out.println("释放锁");
    }

    public void otherMethod() {
        System.out.println("未同步方法调用成功");
    }
}
